package com.xiezc.controller;

import com.xiaoleilu.hutool.cache.impl.TimedCache;
import com.xiezc.dao.FileInfoRepository;
import com.xiezc.entity.FileInfo;
import com.xiezc.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Callable;

/**
 * 下载文件的action
 * Created by wb-xzc291800 on 2017/6/15.
 */
@RestController
@RequestMapping("download")
public class DownLoadAction {

    @javax.annotation.Resource
    private TimedCache timedCache;
    @Value("${filePath}")
    private String filePath;
    @javax.annotation.Resource
    private FileInfoRepository fileInfoRepository;

    /**
     * 下载文件
     *
     * @return
     */
    @RequestMapping(value = "/downloadFile", method = RequestMethod.POST)
    @ResponseBody
    public Callable<ResponseEntity<Resource>> downloadFile(HttpServletRequest request, @RequestBody FileInfo fileInfo) throws FileNotFoundException {
        return () -> {
            User user = (User) request.getAttribute("user");
            //User user = ticketRedisTemplate.opsForValue().get(ticket);
            if (StringUtils.isEmpty(user)) {
                return ResponseEntity.status(401).build();
            }
            Path path = Paths.get(filePath + user.getUserName() + File.separator + fileInfo.getFileMd5());
            if (!Files.exists(path)) {
                return ResponseEntity.status(404).build();
            }
            org.springframework.core.io.Resource resource = new FileSystemResource(path.toFile());
            return ResponseEntity
                    .ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileInfo.getFileName() + "\"")
                    .body(resource);
        };
    }


}
